/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtp.filter;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

import com.googlecode.asyncmail.smtp.SMTPRequestImpl;
import com.googlecode.asyncmail.smtp.SMTPResponse;

import java.util.Locale;

/**
 * Filter to convert SMTPResponse to String Objects
 * 
 */
public class SMTPResponseFilter extends IoFilterAdapter {

    private static final String SCHEDULE_CLOSE_ATTRIBUTE = SMTPRequestFilter.class
            .getName()
            + ".closeAttribute";

    @Override
    public void messageReceived(NextFilter arg0, IoSession arg1, Object arg2)
            throws Exception {
        if (arg2 instanceof String) {
            String cmdString = (String) arg2;
            if (cmdString != null) {
                cmdString = cmdString.trim();
            }

            String curCommandArgument = null;
            String curCommandName = null;
            int spaceIndex = cmdString.indexOf(" ");
            if (spaceIndex > 0) {
                curCommandName = cmdString.substring(0, spaceIndex);
                curCommandArgument = cmdString.substring(spaceIndex + 1);
            } else {
                curCommandName = cmdString;
            }
            curCommandName = curCommandName.toUpperCase(Locale.US);

            arg0.messageReceived(arg1, new SMTPRequestImpl(curCommandName,
                    curCommandArgument));
        } else {
            super.messageReceived(arg0, arg1, arg2);
        }
    }

    @Override
    public void messageSent(NextFilter arg0, IoSession arg1, Object arg2)
            throws Exception {
        super.messageSent(arg0, arg1, arg2);
        // System.err.println("### "+arg2);
        if (arg1.containsAttribute(SCHEDULE_CLOSE_ATTRIBUTE)) {
            // Close the session if no more scheduled writes are there.
            if (arg1.getScheduledWriteRequests() == 0) {
                arg1.close();
            }
        }
    }

    @Override
    public void filterWrite(NextFilter arg0, IoSession arg1,
            WriteRequest writeRequest) throws Exception {

        if (writeRequest.getMessage() instanceof SMTPResponse) {
            SMTPResponse response = (SMTPResponse) writeRequest.getMessage();
            if (response != null) {
                // Iterator i = esmtpextensions.iterator();
                for (int k = 0; k < response.getLines().size(); k++) {
                    StringBuffer respBuff = new StringBuffer(256);
                    respBuff.append(response.getRetCode());
                    if (k == response.getLines().size() - 1) {
                        respBuff.append(" ");
                        respBuff.append(response.getLines().get(k));
                        arg0.filterWrite(arg1, new WriteRequest(respBuff
                                .toString()));
                    } else {
                        respBuff.append("-");
                        respBuff.append(response.getLines().get(k));
                        arg0.filterWrite(arg1, new WriteRequest(respBuff
                                .toString()));
                    }
                }

                if (response.isEndSession()) {
                    arg1.setAttribute(SCHEDULE_CLOSE_ATTRIBUTE);
                    // arg0.filterClose(arg1);
                    // arg1.close();
                }
            }
        } else {
            super.filterWrite(arg0, arg1, writeRequest);
            // arg0.filterWrite(arg1, writeRequest);
        }

    }
}
